import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'
import { SignJWT } from 'jose'
import { cookies } from 'next/headers'

const prisma = new PrismaClient()
const JWT_SECRET = new TextEncoder().encode(
  process.env.JWT_SECRET || 'your-secret-key'
)

/**
 * @swagger
 * /api/auth/login:
 *   post:
 *     summary: 用户登录
 *     requestBody:
 *       content:
 *         application/json:
 *           example:
 *             email: "user@example.com"
 *             password: "123456"
 *     responses:
 *       200:
 *         content:
 *           application/json:
 *             example:
 *               user:
 *                 id: "123"
 *                 email: "user@example.com"
 *                 role: "管理员"
 */

export async function POST(request: Request) {
  try {
    const { email, password } = await request.json()
    console.log('Login attempt for:', email)

    const user = await prisma.user.findUnique({
      where: { email },
      select: {
        id: true,
        email: true,
        password: true,
        role: true,
        name: true
      }
    })
    console.log('Found user:', user)

    if (!user || !user.id) {
      return NextResponse.json({ error: '用户不存在' }, { status: 401 })
    }

    if (!user.password) {
     // 返回错误提示，要求用户通过密码重置流程设置密码
     return NextResponse.json({ 
        error: '请先设置密码',
        code: 'PASSWORD_NOT_SET'
      }, { status: 400 })
    }

    const trimmedPassword = password.trim() // 移除可能的空格
    console.log('trimmedPassword',trimmedPassword)
    console.log('password',user.password)

    console.log('Raw password length:', password.length)
    console.log('Trimmed password length:', trimmedPassword.length)
    console.log('Stored hash length:', user.password.length)
    console.log('salt pwd',await bcrypt.hash('123456', 10) )
    const isValid = await bcrypt.compare(trimmedPassword, user.password)
    console.log('Password valid:', isValid)
    
    if (!isValid) {
      return NextResponse.json({ error: '密码错误' }, { status: 401 })
    }

    const payload = {
      userId: user.id,
      email: user.email,
      role: user.role || 'user',
      name: user.name || email
    }
    console.log('JWT payload:', payload)

    if (!payload.userId) {
      throw new Error('Invalid payload: missing userId')
    }

    if (isValid) {
      const token = await new SignJWT({ 
        userId: user.id,
        email: user.email,
        role: user.role 
      })
        .setProtectedHeader({ alg: 'HS256' })
        .setExpirationTime('24h')
        .sign(JWT_SECRET)

      const response = NextResponse.json(
        { user: { id: user.id, email: user.email, role: user.role } },
        { status: 200 }
      )

      response.cookies.set({
        name: 'token',
        value: token,
        httpOnly: false,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        path: '/',
        maxAge: 60 * 60 * 24
      })

      console.log('Setting cookie:', token)
      return response
    }

  } catch (error: any) {
    console.error('Login error details:', {
      message: error.message,
      stack: error.stack
    })
    return NextResponse.json({ 
      error: '登录失败',
      details: error.message 
    }, { status: 500 })
  }
} 